package com.kfpanda.search.index.context;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Repository;

import com.util.common.FilePath;

@Repository("indexOXMFactory")
public class IndexOXMFactory {

	private static final String FILE_NAME = FilePath.getAbsolutePathWithClass() 
									+ "com/kfpanda/search/index/context/index.xml";
	private IndexResource indexResource;
	private Marshaller marshaller;
	private Unmarshaller unmarshaller;

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

	public void saveIndexResource() throws IOException, JAXBException {
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(FILE_NAME);
			this.marshaller.marshal(indexResource, new StreamResult(os));
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}

	public IndexResource loadIndexResource() throws IOException, JAXBException {
		FileInputStream is = null;
		try {
			is = new FileInputStream(FILE_NAME);
			this.indexResource = (IndexResource) this.unmarshaller
					.unmarshal(new StreamSource(is));
			return this.indexResource;
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	public void go() throws IOException, JAXBException {
		indexResource = getIndexResource();

//		saveIndexResource();
		loadIndexResource();
		System.out.println(indexResource.getIndexs().size());
	}

	private IndexResource getIndexResource() {
		return new IndexResource();
	}
	
}
